import Mock from "mockjs"
import MenuData from './menu.json'

Mock.mock('/login', 'post', (config) => {
  const user = JSON.parse(config.body)
  const username = user.username
  const password = user.password
  const luser = JSON.parse(localStorage.getItem('user'))
  if (username === luser.username && password === luser.password) {
    return {
      "code": 200,
      "result": {
        "apikey": "b9b3a96f7554e3bead2eccf16506c13e"
      }
    }
  } else {
    return {
      "code": 404,
      "result": {}
    }
  }
})

Mock.mock('/getUserList', 'post', (config) => {
  const page = JSON.parse(config.body)
  //当前页
  const currentPage = page.currentPage
  //没有显示条数
  const pageSize = page.pageSize
  //偏移(取数据的下标)
  const offset = (currentPage - 1) * pageSize
  //搜索条件
  const search = page.search
  //从localStorage中取出json格式的用户列表
  const userlist = JSON.parse(localStorage.getItem('userlist'))
  //根据用户名查询符合条件的数据
  if (search != '') {
    userlist.result = userlist.result.filter(value => {
      return value.name == search
    })
    userlist.total = userlist.result.length
    return userlist
  }

  console.log(userlist.result)
  //根据用户传入的条件，从数组中查询对应的数据
  const res = userlist.result.slice(offset, offset + pageSize)

  userlist.result = res

  return userlist
})

Mock.mock('/addUser', 'post', (config) => {
  const user = JSON.parse(config.body)
  console.log(user)
  //用户id
  const id = user.id
  //用户姓名
  const username = user.username
  //用户地址
  const address = user.address
  //从localStorage中取出用户列表并转成对象
  const userList = JSON.parse(localStorage.getItem('userlist'))
  userList.total += 1
  userList.result.push(user)

  localStorage.setItem('userlist', JSON.stringify(userList))
  return userList
})

Mock.mock('/delUser', 'post', (config) => {
  const body = JSON.parse(config.body)

  //从localStorage中取出用户列表并转成对象
  const userList = JSON.parse(localStorage.getItem('userlist'))

  userList.total -= 1

  const arr = userList.result.filter(value => value.id != body.id)

  userList.result = arr;

  localStorage.setItem('userlist', JSON.stringify(userList))
  return userList
})

Mock.mock('/getMenuList', 'post', (config) => {
  return MenuData
})

Mock.mock('/getUserById', 'get', (config) => {
  const body = JSON.parse(config.body)

  console.log(body.id)

  //从localStorage中取出用户列表并转成对象
  const userList = JSON.parse(localStorage.getItem('userlist'))

  return userList.result.find(value => value.id == body.id)

})

Mock.mock('/editUser', 'post', (config) => {
  const body = JSON.parse(config.body)

  //从localStorage中取出用户列表并转成对象
  const userList = JSON.parse(localStorage.getItem('userlist'))
  
  userList.result.forEach(value=>{
     if(value.id == body.id){
       value.name = body.name
       value.address = body.address
     }
  })
  localStorage.setItem('userlist',JSON.stringify(userList))
  return userList
})
